package com.arron.jvm.ref;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * @Classname WeakHashMapDemo
 * @Date 2020/8/24 0:12
 * @Created by 刘
 */
public class WeakHashMapDemo {


    //软引用，弱引用，适合用于缓存方面，当内存不足是gc回收，
    //WeakHashMap 也可以用于缓存，当key为null时，也会被gc回收
    public static void main(String[] args) {
//        myHashMap();
        myWeakHashMap();
    }

    private static void myWeakHashMap() {

        Map<Integer, String> map = new WeakHashMap<>();
        Integer key = new Integer(2);
        String value = "WeakHashMap";
        map.put(key,value);
        System.out.println("=============GC之前==============");
//        System.gc();
        System.out.println(map);

        key = null;
        System.out.println(map);

        System.gc();
        System.out.println("=============GC之后==============");
        System.out.println(map+"\tsize:"+map.size());

    }

    private static void myHashMap() {
        //普通hashMap
        Map<Integer, String> map = new HashMap<>();
        Integer key = new Integer(1);
        String value = "HashMap";
        map.put(key,value);
        System.out.println("=============GC之前==============");
        System.out.println(map);

        key = null;
        System.out.println(map);

        System.gc();
        System.out.println("=============GC之后==============");
        System.out.println(map);
    }

}
